package cn.lwj.webService.util;

import cn.lwj.webService.base.DaoTool;
import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import java.io.InputStream;
import java.sql.Blob;
import org.hibernate.LobHelper;

public class BlobConverter implements Converter   {
	
	public boolean canConvert(Class clazz) {
		return Blob.class.isAssignableFrom(clazz);

	}

	public void marshal(Object value, HierarchicalStreamWriter writer,MarshallingContext context) {
		if(value!=null){
			String str = "";
			Blob blob = (Blob)value;
			try{
				InputStream in = blob.getBinaryStream();
				byte[] buff=new byte[(int) blob.length()];
				for(int i=0;(i=in.read(buff))>0;){  
		            str=str+new String(buff);  
		        } 
				if(in!=null){
					in.close();
					in = null;
				}
				writer.setValue(str);
			}catch(Exception e){
				throw new ConversionException(e.getMessage(), e);
			}
			
		}
	}

	public Object unmarshal(HierarchicalStreamReader reader,UnmarshallingContext context) {
		Blob blob = null;
		try {
			if(reader.getAttribute("xsi:nil")!=null&&reader.getAttribute("xsi:nil").toString().equals("true")&&(reader.getValue()==null||reader.getValue().trim().equals(""))){
				return null;
			}
			else if(reader.getValue()!=null&&!reader.getValue().trim().equals("")){
				byte[] bytes = reader.getValue().getBytes("UTF-8");
		        //得到LobHelper
				DaoTool daoTool = (DaoTool)SpringBeanHelper.getBean("daoTool");
		        LobHelper lobHelper = daoTool.getCurrentSession().getLobHelper();
		        blob = lobHelper.createBlob(bytes);
			}
		} catch (Exception e) {
			throw new ConversionException(e.getMessage(), e);
		}
		return blob;
	}

}
